#include "common.h"

/*** Client for echo-server ***/

int main() {
    int sockfd;
    struct sockaddr_in addr;
    char buf[BUF_SIZE];
    char message[BUF_SIZE];
    
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Error in socket creation");
        return errno;
    }

    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(MY_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    
    if (connect(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        perror("Error in connection");
        close(sockfd);
        return errno;
    }
    
    printf("Please, enter your message:\n");
    scanf("%[^\n]s", message);
    int send_result = send(sockfd, message, sizeof(message), 0);
    if (send_result == -1 || send_result < sizeof(message)) {
        perror("Error in sending data");
        close(sockfd);
        return errno;        
    }
    int recv_result = recv(sockfd, buf, sizeof(message), 0);
    if (recv_result == -1 || recv_result < sizeof(message)) {
        perror("Error in receiving data");
        close(sockfd);
        return errno;        
    }
    
    printf("Received: %s\n", buf);
    close(sockfd);
    return 0;
}
